package com.ybkj.o2o.zhuanche.common.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Component
public class SalesApi {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;
    //zhyu
//    private static final String SERVER_ADDRESS = "http://192.168.0.203:8499/";
    @Value("{spring.sales_url}")
    private String SERVER_ADDRESS;

    public static final String API_SERVICE_ID = "sales";

    public static final String UPDATE_V4 = "api/coupons/v4/update/{id}?status={status}&appKey={appKey}";

    /**
     * 设置指定优惠券状态.
     * @param id     优惠券id
     * @param status 要修改的状态.
     * @param appKey 系统key.
     */

    public void updateV4(Long id, Integer status, String appKey) {
        String buildApi = getRestUri(API_SERVICE_ID, SERVER_ADDRESS) + UPDATE_V4;
        buildApi = buildApi.replaceAll("\\{id\\}", String.valueOf(id));
        restTemplate.put(buildApi, null, status, appKey);
    }

    /**
     * 拼接用户项目服务器地址.
     *
     * @param serviceId   查询地址的名称
     * @param fallbackUrl 备用地址
     * @return 服务器地址
     */

    public String getRestUri(String serviceId, String fallbackUrl) {
        URI uri;
        try {
            ServiceInstance serviceInstance = loadBalancer.choose(serviceId);
            uri = serviceInstance.getUri();
        } catch (RuntimeException ex) {
//      ex.printStackTrace();
            uri = URI.create(fallbackUrl);
        }

        String http = uri.toString();
        if (!http.endsWith("/")) {
            return http + "/";
        }
        return http;

    }
}
